package com.jxb.dp;

/**
 * 最大子序和
 * nums = [-2,1,-3,4,-1,2,1,-5,4]
 * 连续子数组[4,-1,2,1] 的和最大，为6 。
 */
public class MaximumSubarray_53 {

    public static void main(String[] args) {
        int[] nums = {-2,1,-3,4,-1,2,1,-5,4};
        System.out.println(maxSubArray1(nums));
    }

    //确定状态转移公式：newSum = max(nums[i],(sum+nums[i]))
    //初始化dp数组：dp[i] = max(nums[i],(dp[i-1]+nums[i]))
    //根据条件开始遍历并实现状态转移公式
    //时间复杂度O(n),空间复杂度O(n)
    public static int maxSubArray(int[] nums) {
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int result = dp[0];
        for (int i = 1;i<nums.length;i++) {
            dp[i] = Math.max(dp[i-1]+nums[i],nums[i]);
            if (result < dp[i]) {
                result = dp[i];
            }
        }
        return result;
    }

    //时间复杂度O(n),空间复杂度O(1)
    public static int maxSubArray1(int[] nums) {
        int result = nums[0];
        int pre = result;
        for (int i = 1;i<nums.length;i++) {
            pre = Math.max(pre + nums[i],nums[i]);
            if (pre > result) {
                result = pre;
            }
        }
        return result;
    }





}
